package com.jotta.client;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.jotta.client.communicate.Configuration;
import com.jotta.client.communicate.ServerCommunicator;
import com.jotta.client.communicate.StateOfClient;
import com.jotta.client.exception.NetworkException;
import com.jotta.client.exception.ServerException;
import com.jotta.client.setting.SettingManager;
import com.jotta.client.utility.Utility;

public class Login extends Activity implements View.OnClickListener, Runnable,
		View.OnKeyListener {
	private Button btnLogin;
	private EditText txtUsername, txtPassword;
	private CheckBox checkBoxAutoLogin;

	ServerCommunicator communicator;
	private ProgressDialog m_ProgressDialog;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		btnLogin = (Button) findViewById(R.id.login_btnLogin);
		btnLogin.setOnClickListener(this);

		txtUsername = (EditText) findViewById(R.id.login_txtusername);
		txtPassword = (EditText) findViewById(R.id.login_txtpassword);
		checkBoxAutoLogin = (CheckBox) findViewById(R.id.login_chkboxAutoLogin);

		txtPassword.setOnKeyListener(this);

		Configuration.prepareConfiguration(this);
	}

	@Override
	public void onClick(View v) {
		if (v == btnLogin) {
			startThreadToLogIn();
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if ((event.getAction() == KeyEvent.ACTION_DOWN)
				&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
			startThreadToLogIn();
		}
		return false;

	}

	private void startThreadToLogIn() {
		// Start new thread to log in to server & show progress bar
		Thread thread = new Thread(this);
		thread.start();

		// initialize progress bar
		m_ProgressDialog = Utility.getProgressBar(Login.this, Configuration.getRes());
		m_ProgressDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.login_menu_login:
			// Start new thread to log in to server & show progress bar
			Thread thread = new Thread(this);
			thread.start();

			// initialize progress bar
			m_ProgressDialog = Utility.getProgressBar(Login.this, Configuration.getRes());
			m_ProgressDialog.show();
			return true;
		case R.id.login_menu_quit:
			quit();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void quit() {
		finish();
	}

	/*
	 * Log in to server & notified to handler when finished
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		Configuration
				.setStateOfClient(StateOfClient.GETTING_SERVER_INFORMATION);
		String message = logIn();

		Bundle bundle = new Bundle();
		bundle.putString(Configuration.SERVER_MESSAGE_KEY, message);
		Message msg = new Message();
		msg.setData(bundle);
		loginFinishedhandler.sendMessage(msg);
		Configuration.setStateOfClient(StateOfClient.OFFLINE);
	}

	/**
	 * Log in
	 * 
	 * @return Message from server
	 */
	private String logIn() {
		try {
			String username = txtUsername.getText().toString().trim();
			String password = txtPassword.getText().toString().trim();
			boolean isAutoLogin = checkBoxAutoLogin.isChecked();

			// log in
			communicator = ServerCommunicator.getInstance(updateProgressBarHandler);
			communicator.logIn(username, password);

			SettingManager.getInstance().setUserInfo(username, password,
					isAutoLogin);

			return Configuration.GET_DATA_SUCCESSFUL_MESSAGE;
		} catch (ServerException e) {
			return e.getErrorMessage();
		} catch (NetworkException e) {
			return e.getErrorMessage();
		} catch (Exception e) {
			if (e.getMessage() != null)
				return e.getMessage();
			return e.toString();
		}
	}

	/** update progress of progress bar */
	private Handler updateProgressBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int progress = msg.getData().getInt(
					Configuration.PROGRESS_BAR_PERCENT);
			if (m_ProgressDialog != null) {
				m_ProgressDialog.setProgress(progress);
			}
		}
	};

	/** When Log in finished dismiss progress dialog and start ListItem Activity */
	private Handler loginFinishedhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			m_ProgressDialog.dismiss();
			String message = msg.getData().getString(
					Configuration.SERVER_MESSAGE_KEY);
			if (!message.equals(Configuration.GET_DATA_SUCCESSFUL_MESSAGE)) {
				Utility.getAlertDialog(Login.this, Configuration.getRes(),
                        message).show();
			} else {
				try {
					// start new activity
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), ListItem.class);
					startActivity(intent);
					finish();
				} catch (Exception e) {
					Utility.getAlertDialog(getApplicationContext(),
                            Configuration.getRes(), e.getMessage()).show();
				}
			}
		}
	};
}